<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>发布需求列表</span>
        <el-input
          v-model="searchQuery"
          placeholder="搜索宠物类型"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          style="width: 200px; float: right; margin-left: 10px;">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch">
          </el-button>
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="handleCreateDemand"
          style="float: right;">
          发布新需求
        </el-button>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="demands.length === 0" class="empty-tip">
        <el-empty description="暂无发布需求"></el-empty>
      </div>

      <div v-else>
        <pre v-if="isDebug" style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin-bottom: 15px; overflow: auto; max-height: 200px;">
          {{ JSON.stringify(demands, null, 2) }}
        </pre>
        <el-table :data="demands" stripe>
          <el-table-column prop="id" label="ID" width="60"></el-table-column>
          <el-table-column prop="petName" label="宠物名称" width="100"></el-table-column>
          <el-table-column prop="petType" label="宠物类型" width="100"></el-table-column>
          <el-table-column prop="petAge" label="宠物年龄" width="80"></el-table-column>
          <el-table-column prop="vaccineRecord" label="疫苗记录"></el-table-column>
          <el-table-column prop="dietaryHabits" label="饮食习惯"></el-table-column>
          <el-table-column label="宠物性别" width="80">
            <template slot-scope="scope">
              {{ scope.row.petGender === '0' ? '公' : '母' }}
            </template>
          </el-table-column>
          <el-table-column prop="homeAddress" label="家庭住址"></el-table-column>
          <el-table-column prop="ownerRequirements" label="主人要求"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <template v-if="isCurrentUserDemand(scope.row)">
                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" style="color: #F56C6C">删除</el-button>
              </template>
              <template v-else>
                <el-button type="text" icon="el-icon-message" @click="handlePrivateMessage(scope.row)">私信</el-button>
                <el-button type="text" icon="el-icon-s-order" style="color: #67C23A;" @click="handleAccept(scope.row)">接单</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 发布需求对话框 -->
    <el-dialog
      title="发布新需求"
      :visible.sync="dialogVisible"
      width="70%">
      <el-form :model="demandForm" :rules="demandRules" ref="demandForm">
        <el-form-item label="宠物名称" prop="petName">
          <el-input v-model="demandForm.petName" placeholder="请输入宠物名称"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型" prop="petType">
          <el-input v-model="demandForm.petType" placeholder="请输入宠物类型"></el-input>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="petAge">
          <el-input v-model="demandForm.petAge" placeholder="请输入宠物年龄"></el-input>
        </el-form-item>
        <el-form-item label="疫苗记录" prop="vaccineRecord">
          <el-input v-model="demandForm.vaccineRecord" placeholder="请输入疫苗接种记录"></el-input>
        </el-form-item>
        <el-form-item label="饮食习惯" prop="dietaryHabits">
          <el-input v-model="demandForm.dietaryHabits" placeholder="请输入饮食习惯"></el-input>
        </el-form-item>
        <el-form-item label="宠物性别" prop="petGender">
          <el-radio-group v-model="demandForm.petGender">
            <el-radio label="0">公</el-radio>
            <el-radio label="1">母</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家庭住址" prop="homeAddress">
          <el-input
            v-model="demandForm.homeAddress"
            placeholder="请输入您的家庭住址"
          ></el-input>
        </el-form-item>
        <el-form-item label="主人要求" prop="ownerRequirements">
          <el-input
            type="textarea"
            v-model="demandForm.ownerRequirements"
            :rows="5"
            placeholder="请输入主人要求"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDemand">发 布</el-button>
      </span>
    </el-dialog>

    <!-- 私信对话框 -->
    <el-dialog
      title="私信宠物主人"
      :visible.sync="privateMessageDialogVisible"
      width="70%">
      <el-form :model="privateMessageForm" :rules="privateMessageRules" ref="privateMessageForm">
        <el-form-item label="消息内容" prop="message">
          <el-input
            type="textarea"
            v-model="privateMessageForm.message"
            :rows="10"
            placeholder="请输入消息内容"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="privateMessageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendPrivateMessage">发 送</el-button>
      </span>
    </el-dialog>

    <!-- 接单对话框 -->
    <el-dialog
      title="接单确认"
      :visible.sync="acceptDialogVisible"
      width="70%">
      <el-form :model="acceptForm" :rules="acceptRules" ref="acceptForm" label-width="100px">
        <el-form-item label="预计服务时间" prop="serviceTime">
          <el-date-picker
            v-model="acceptForm.serviceTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报价" prop="price">
          <el-input v-model.number="acceptForm.price" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="服务说明" prop="description">
          <el-input
            type="textarea"
            v-model="acceptForm.description"
            :rows="5"
            placeholder="请详细描述您的服务内容、经验和服务保障..."
          ></el-input>
        </el-form-item>
        
        <!-- 需求信息展示 -->
        <div class="demand-info">
          <div class="title">需求信息</div>
          <div class="info">
            <div class="info-item">
              <label>宠物名称:</label>
              <span>{{ currentDemand ? currentDemand.petName : '' }}</span>
            </div>
            <div class="info-item">
              <label>宠物类型:</label>
              <span>{{ currentDemand ? currentDemand.petType : '' }}</span>
            </div>
            <div class="info-item">
              <label>主人要求:</label>
              <span>{{ currentDemand ? currentDemand.ownerRequirements : '' }}</span>
            </div>
          </div>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="acceptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAccept">确认接单</el-button>
      </span>
    </el-dialog>

    <!-- 接单成功对话框 -->
    <el-dialog
      title="接单成功"
      :visible.sync="acceptSuccessDialogVisible"
      width="500px">
      <el-result icon="success" title="接单成功" subTitle="请等待主人确认，或前往任务节点管理页面查看任务">
        <template slot="extra">
          <el-button type="primary" @click="goToTaskNode">前往任务节点</el-button>
          <el-button @click="acceptSuccessDialogVisible = false">关闭</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Offer',
  data() {
    return {
      loading: false,
      demands: [],
      searchQuery: '',
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      userInfo: null,
      isDebug: false,
      demandForm: {
        petName: '',
        petType: '',
        petAge: '',
        vaccineRecord: '',
        dietaryHabits: '',
        petGender: '0',
        homeAddress: '',
        ownerRequirements: ''
      },
      demandRules: {
        petName: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        petType: [
          { required: true, message: '请输入宠物类型', trigger: 'blur' }
        ],
        petAge: [
          { required: true, message: '请输入宠物年龄', trigger: 'blur' }
        ],
        petGender: [
          { required: true, message: '请选择宠物性别', trigger: 'change' }
        ],
        ownerRequirements: [
          { required: true, message: '请输入主人要求', trigger: 'blur' }
        ]
      },
      privateMessageDialogVisible: false,
      privateMessageForm: {
        message: ''
      },
      privateMessageRules: {
        message: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ]
      },
      currentDemand: null,
      // 接单相关数据
      acceptDialogVisible: false,
      acceptForm: {
        serviceTime: [],
        price: 199,
        description: ''
      },
      acceptRules: {
        serviceTime: [
          { required: true, message: '请选择服务时间', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入报价', trigger: 'blur' },
          { type: 'number', min: 1, message: '报价必须大于0', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入服务说明', trigger: 'blur' },
          { min: 20, message: '服务说明不能少于20字', trigger: 'blur' }
        ]
      },
      acceptSuccessDialogVisible: false,
      newOrderId: null
    }
  },
  methods: {
    async getUserInfo() {
      try {
        const res = await request({
          url: '/getInfo',
          method: 'get'
        })
        if (res.user) {
          this.userInfo = res.user
          this.getList()
        }
      } catch (error) {
        this.$message.error('获取用户信息失败')
      }
    },
    getList() {
      this.loading = true
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      
      // 如果有搜索关键词，添加到请求参数中
      if (this.searchQuery) {
        params.petType = this.searchQuery.trim()
      }

      request({
        url: '/pet/demand/list',
        method: 'get',
        params: params
      }).then(response => {
        console.log('原始响应数据:', response)
        
        // 检查响应格式并提取数据
        if (response && response.code === 200) {
          // 标准后端成功响应
          if (response.rows && Array.isArray(response.rows)) {
            this.demands = response.rows
            this.total = response.total || this.demands.length
          } else {
            console.error('响应中缺少rows数组:', response)
            this.demands = []
            this.total = 0
          }
        } else if (response && Array.isArray(response)) {
          // 直接返回数组的情况
          this.demands = response
          this.total = response.length
        } else if (response && Array.isArray(response.data)) {
          // data字段中包含数组的情况
          this.demands = response.data
          this.total = response.data.length
        } else {
          // 其他情况
          console.error('未识别的响应格式:', response)
          this.demands = []
          this.total = 0
        }
        
        // 应用搜索过滤
        if (this.searchQuery && this.demands.length > 0) {
          const query = this.searchQuery.toLowerCase().trim()
          this.demands = this.demands.filter(item => 
            item.petType && item.petType.toLowerCase().includes(query)
          )
          this.total = this.demands.length
        }
        
        console.log('处理后的数据:', this.demands)
        this.loading = false
      }).catch(error => {
        console.error('API请求错误:', error)
        this.$message.error('获取数据失败')
        this.demands = []
        this.total = 0
        this.loading = false
      })
    },
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },
    handleCreateDemand() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.demandForm && this.$refs.demandForm.clearValidate();
      });
    },
    submitDemand() {
      this.$refs.demandForm.validate(valid => {
        if (valid) {
          const formData = {
            ...this.demandForm,
            userId: this.userInfo.userId
          }
          request({
            url: '/pet/demand',
            method: 'post',
            data: formData
          }).then(() => {
            this.$message.success('发布需求成功')
            this.dialogVisible = false
            this.getList()
            // 重置表单，包含所有字段
            this.demandForm = {
              petName: '',
              petType: '',
              petAge: '',
              vaccineRecord: '',
              dietaryHabits: '',
              petGender: '0',
              homeAddress: '',
              ownerRequirements: ''
            }
          }).catch(() => {
            this.$message.error('发布需求失败')
          })
        }
      })
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.getList();
    },
    handleEdit(row) {
      this.demandForm = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除该需求吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/pet/demand/${row.id}`,
          method: 'delete'
        }).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {})
    },
    handlePrivateMessage(row) {
      this.privateMessageDialogVisible = true;
      this.currentDemand = row;
      this.$nextTick(() => {
        this.$refs.privateMessageForm && this.$refs.privateMessageForm.clearValidate();
      });
    },
    sendPrivateMessage() {
      this.$refs.privateMessageForm.validate(valid => {
        if (valid) {
          request({
            url: '/pet/demand/message',
            method: 'post',
            data: {
              demandId: this.currentDemand.id,
              message: this.privateMessageForm.message,
              senderId: this.userInfo.userId
            }
          }).then(() => {
            this.$message.success('私信发送成功');
            this.privateMessageDialogVisible = false;
            this.privateMessageForm.message = '';
          }).catch(() => {
            this.$message.error('私信发送失败');
          });
        }
      });
    },
    isCurrentUserDemand(row) {
      return this.userInfo && row.userId === this.userInfo.userId;
    },
    // 接单相关方法
    handleAccept(row) {
      this.currentDemand = row;
      this.acceptDialogVisible = true;
      this.acceptForm = {
        serviceTime: [],
        price: 199,
        description: ''
      };
      this.$nextTick(() => {
        this.$refs.acceptForm && this.$refs.acceptForm.clearValidate();
      });
    },
    submitAccept() {
      this.$refs.acceptForm.validate(valid => {
        if (valid) {
          // 格式化日期时间
          const formatDateTime = (date) => {
            const pad = (num) => String(num).padStart(2, '0');
            return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
          };
          
          // 组装接单数据
          const offerData = {
            demandId: this.currentDemand.id,
            acceptorId: this.userInfo.userId,
            serviceStartTime: formatDateTime(this.acceptForm.serviceTime[0]),
            serviceEndTime: formatDateTime(this.acceptForm.serviceTime[1]),
            price: this.acceptForm.price,
            description: this.acceptForm.description
          };
          
          console.log('提交的接单数据:', offerData); // 调试用
          
          // 调用后端接口
          request({
            url: '/api/pet-care/offers',
            method: 'post',
            data: offerData
          }).then(response => {
            console.log('接单响应:', response); // 调试用
            this.newOrderId = response.id;
            this.acceptDialogVisible = false;
            this.acceptSuccessDialogVisible = true;
            this.$message.success('接单申请已提交');
            this.getList(); // 刷新列表
          }).catch(error => {
            console.error('接单失败:', error);
            this.$message.error('接单失败: ' + (error.response?.data?.message || '请稍后重试'));
          });
        }
      });
    },
    goToTaskNode() {
      this.acceptSuccessDialogVisible = false;
      this.$router.push({
        path: '/pet-care/task-node',
        query: { orderId: this.newOrderId }
      });
    }
  },
  created() {
    this.getUserInfo()
  }
};
</script>

<style scoped>
.loading-container {
  padding: 20px;
}

.empty-tip {
  padding: 50px 0;
  text-align: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.demand-info {
  margin-top: 20px;
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.demand-info .title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

.demand-info .info {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.demand-info .info-item {
  margin-bottom: 8px;
}

.demand-info .info-item label {
  font-weight: bold;
  margin-right: 5px;
  color: #606266;
}
</style>
